package com.wavejo.reactor;
import com.wavejo.reactor.handler.UserHandler;
import com.wavejo.reactor.service.UserService;
import com.wavejo.reactor.service.impl.UserServiceImpl;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

/**
 * @Author WaveHi
 * @Date 27/10/2021 下午 9:48
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Build router
 */
public class Server {

    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("Enter to exit.");
        System.in.read();
    }

    /**
     * 服务器
     * @return
     */
    public RouterFunction<ServerResponse> routerFunction() {
        UserService userService = new UserServiceImpl();
        UserHandler userHandler = new UserHandler(userService);
        return RouterFunctions.route(
                GET("/users/{id}").and(accept(APPLICATION_JSON)),userHandler::getData)
                .andRoute(GET("/users").and(accept(APPLICATION_JSON)),userHandler::getAllUser);
    }

    /**
     * 创建路由
     */
    public void createReactorServer() {
        //适配
        RouterFunction<ServerResponse> router = routerFunction();
        HttpHandler httpHandler = toHttpHandler(router);
        ReactorHttpHandlerAdapter rha = new ReactorHttpHandlerAdapter(httpHandler);

        //创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(rha).bindNow();
    }
}
